/**
 * Created by yangchen on 2019/4/4
 * */

/**
 * 云南 浙江 公共模块
 */
class YZCommon {
  /**
   * hack年报填写数据 年报字段有变化
   * @param inputData 本年数据
   * @param lastYearData 上年数据
   * @param sheet 报表类型
   * @returns {{}}
   */
  hackYearReportInput(inputData, lastYearData, sheet) {
    let keys = Object.keys(lastYearData);
    let reg = /xx_([0-9]*)_b([yn]+)s/;
    let results = keys.reduce((result, key) => {
      if (reg.test(key)) {
        if (sheet === 'profit') {
          result[key.replace('bns', 'sns')] = lastYearData[key];
        } else if (sheet === 'cash') {
          result[key.replace('bys', 'sys')] = lastYearData[key];
        }
      }
      return result;
    }, {});
    return { ...inputData, ...results };
  }

  /**
   * 抓取待办事项
   */
  captureTodo() {
    const trs = $('#sbxm_zcsb_menu tr').toArray();
    return trs
      .map(tr => {
        const declareType = $(tr)
          .find('td:visible:first')[0]
          .innerText.trim();
        const SBZT = $(tr)
          .find('td:visible:last')[0]
          .innerText.trim();
        const declareTime = SBZT && SBZT.includes(' ') ? SBZT.split(' ')[0] + ' 00:00:00' : '';
        const state = SBZT.includes('已') ? '已申报' : '未申报';
        return {
          declareTime,
          declareType: this.replaceSpecialSign(declareType),
          state
        };
      })
      .filter(
        item =>
          /增值税|财务报表|附加税|企业所得税/.test(item.declareType)
          && !/往期/.test(item.declareType)
      );
  }

  /**
   * 从页面中获取报表信息
   */
  async captureDataFromPage() {
    const reportInfoFromTodo = this.captureTodo();
    console.log('success', reportInfoFromTodo);

    if (!reportInfoFromTodo.length) {
      alert('请本期申报完成后，再同步申报表信息！');
    }
    window.postMessage(
      {
        event: 'syncReportInfoInSaas',
        data: {
          syncReportInfo: reportInfoFromTodo
        }
      },
      '*'
    );
  }

  /**
   * 开始同步申报表信息
   */
  startGetReportInfo() {
    if (
      !/https:\/\/etax.([\s\S]+?).chinatax.gov.cn\//.test(window.location.href)
    ) {
      alert('请在首页进行同步申报种类！');
      return;
    }
    window.open('/zjgfzjdzswjsbweb/pages/sb/nssb/sb_nssb.html');
  }

  /**
   * 开始同步申报表
   */
  startGetReport() {
    const tables = $('table:visible').toArray();
    if (!tables) {
      alert('请到对应的申报界面进行同步申报表');
      return;
    }

    const result = [...tables].map(table => this.transformTableToArray(table));
    console.log(result);
    let declareType = result[0][0][0].val.trim();
    declareType = declareType.includes('增值税')
      ? '增值税'
      : this.replaceSpecialSign(declareType);
    declareType = this.replaceName(declareType);

    // 特殊情况处理 当第一行是无意义的提示，不是报表名时，会匹配不上
    if (!declareType) {
      declareType = this.replaceName(result[0][1][0].val.trim());
    }
    window.postMessage(
      {
        event: 'syncReportInSaas',
        data: {
          detail: result,
          state: '已申报',
          declareType
        }
      },
      '*'
    );
  }

  /**
   * 将dom转换为二维数组
   * @param {Array} table
   */
  transformTableToArray(table) {
    // 集合所有tr即每一行
    const trs = $(table)
      .find('tr:visible')
      .toArray();

    // 构建二维数组，并构建每一行每一列的数据
    const result = trs.map(tr => {
      let tds = $(tr)
        .find('td:visible')
        .toArray();
      if (tds && tds.length) {
        tds = tds.map(td => {
          const $td = $(td);
          const inputs = $td.find('input');
          let val = '';
          // 若存在input，则为输入框
          if (inputs.length) {
            // 获取输入
            val = $(inputs[0]).val();
            if (['N', 'Y'].includes(val)) {
              val = val === 'N' ? '否' : '是';
            }
            let text = $td.text().replace(/\s/g, '');
            // 存在文本+输入框情况 需都抓取 排除-- （数额为空填充）
            if (text && text !== '--') {
              val = text + val;
            }
          } else {
            val = $td.text().replace(/\s/g, '');
          }
          // return val;
          return {
            val,
            rowspan: $td.attr('rowspan') || '1',
            colspan: $td.attr('colspan') || '1'
          };
        });
      }
      return tds;
    });
    return result;
  }

  /**
   * 替换特殊符号
   * @param {String} str
   */
  replaceSpecialSign(str) {
    return str.replace(/（/g, '(').replace(/）/g, ')');
  }

  replaceName(name) {
    const names = [
      '企业所得税月', '企业所得税年', '增值税', '个人所得税', '财务报表', '附加税'
    ];
    return names.find(n => name.includes(n));
  }
}

const YZ = new YZCommon();

export default YZ;
